let {Server} = require('ws');

let ws = new Server({port: 5050});

let rom = require('./db/ROM');

// 记录连接情况
let clients = [];

function connection(client) {
  console.log('有客到:');
  client.on('message', async data => {
    let parseData = JSON.parse(data);

    let {type, userId, otherId} = parseData;

    if (type === 'open') {
      // 已经建立连接
      clients.push({client, userId});
      // [{client,userId:1},{client,userId:2},{client,userId:3}]

      let resUser = await rom.query('select * from user where userid = ' + userId);
      let resOther = await rom.query('select * from user where userid = ' + otherId);
      if (resUser.length === 0 || resOther.length === 0) {
        client.send(JSON.stringify({type: 'err', msg: '聊天人失效'}));
      }
    } else if (type === 'msg') {
      // 发送信息
      let {msg, userId, otherId} = parseData;
      // 数据库中必须要有userId, otherId
      // 遍历 {client,3} 3
      // client.send()
      clients.filter(item => item.userId === otherId).map(item => item.client.send(JSON.stringify({
        msg,
        otherId: userId,
        type: 'msg'
      })));
    }
  });

}

ws.on('connection', connection);
